package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.FlexShelfOffOrderDetailNewAdapter;
import com.mflex.WHSmartWhouseAd.model.M_WHSMTList;
import com.mflex.WHSmartWhouseAd.model.MaterialDetailForSMTModel;
import com.mflex.WHSmartWhouseAd.model.RequestModel;
import com.mflex.WHSmartWhouseAd.model.TaskPKGInfo;
import com.mflex.WHSmartWhouseAd.model.WHPKGLocData;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.reflect.TypeToken;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class FlexShelfOffOrderDetailLotNewActivity extends AppCompatActivity {

    EditText stvSMTLot;
    EditText stvProduct;
    EditText stvFlexProduct;
    EditText stvFloor;
    EditText stvOrderQty;
    EditText stvZoom;
    EditText stvPlanQty;
//    EditText stvScanQty;
//    EditText stvVehicleNo;
    EditText stvCarNo;
    EditText stvPKGNo;
    EditText stvPKGType;
    EditText ScanPlateQty;
    EditText stvIsFeedingQty;
    EditText stvFeedingQty;
    ListView lvList;

    Button buttonClear;
    Button buttonSubmit;

    MiniLoadingDialog mMiniLoadingDialog;

    String userName;
    String userPassword;

    String TaskNo;

    private double scanQty;

    private String ShrinkType;

    List<String> scanList = new ArrayList<>();
    List<TaskPKGInfo> taskPKGInfoList = new ArrayList<>();
    List<WHPKGLocData> whpkgLocDataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_flex_shelf_off_order_detail_lot_new);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        stvSMTLot = findViewById(R.id.stvSMTLot);
        stvProduct = findViewById(R.id.stvProduct);
        stvFlexProduct = findViewById(R.id.stvFlexProduct);
        stvFloor = findViewById(R.id.stvFloor);

        stvOrderQty = findViewById(R.id.stvOrderQty);
        stvZoom = findViewById(R.id.stvZoom);
        stvPlanQty = findViewById(R.id.stvPlanQty);

        stvCarNo = findViewById(R.id.stvCarNo);
        stvPKGNo = findViewById(R.id.stvPKGNo);
        stvPKGType = findViewById(R.id.stvPKGType);

        ScanPlateQty = findViewById(R.id.ScanPlateQty);
        stvIsFeedingQty = findViewById(R.id.IsFeedingQty);
        stvFeedingQty = findViewById(R.id.FeedingQty);

        lvList = findViewById(R.id.lvList);

        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_submit);

        Intent intent = getIntent();

        userName = intent.getStringExtra("userName");
        TaskNo = intent.getStringExtra("TaskNo");
        userPassword = intent.getStringExtra("userPassword");

        stvOrderQty.setText(intent.getStringExtra("OrderQty"));
        stvSMTLot.setText(intent.getStringExtra("SMTLot"));
        stvFloor.setText(intent.getStringExtra("floor"));
        stvFlexProduct.setText(intent.getStringExtra("FLEXProduct"));
        stvProduct.setText(intent.getStringExtra("SMTProduct"));

        stvZoom.setText(intent.getStringExtra("ZoomScale"));
        stvPlanQty.setText(intent.getStringExtra("PlanQty"));
        stvIsFeedingQty.setText(intent.getStringExtra("IsFeedingQty"));
        stvPKGType.setText(intent.getStringExtra("ProductType"));

        Type listType = new TypeToken<List<MaterialDetailForSMTModel>>() {
        }.getType();
        taskPKGInfoList = (List<TaskPKGInfo>) JsonUtil.fromJson(intent.getStringExtra("TaskPKGInfoList"), listType);

//        String firstZoomScale = taskPKGInfoList.get(0).getShrinkType();
//        for(TaskPKGInfo taskPKGInfo : taskPKGInfoList) {
//            if(StringUtils.equals(firstZoomScale, taskPKGInfo.getShrinkType())) {
//                taskFirstPKGInfoList.add(taskPKGInfo);
//            }
//        }

        FlexShelfOffOrderDetailNewAdapter FlexShelfOffOrderDetailNewAdapter = new FlexShelfOffOrderDetailNewAdapter(FlexShelfOffOrderDetailLotNewActivity.this, taskPKGInfoList);
        lvList.setAdapter(FlexShelfOffOrderDetailNewAdapter);

        ShrinkType = taskPKGInfoList.get(0).getShrinkType();

        buttonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(FlexShelfOffOrderDetailActivity.this, FlexShelfOffOrderActivity.class);
//                startActivity(intent);
                setResult(RESULT_OK);
                finish();
            }
        });
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMiniLoadingDialog.show();
                M_WHSMTList model = new M_WHSMTList(stvSMTLot.getText().toString(), "", userName, userPassword, whpkgLocDataList,
                        TaskNo, "", stvProduct.getText().toString(), "", "");RequestModel requestModel = new RequestModel();
                requestModel.setJson(JsonUtil.toJson(model));
                String json = JsonUtil.toJson(requestModel);
                System.out.println(json);
                XHttp.post("api/WHSmartWhousePDA/CommitFlexFeed")
                        .upJson(JsonUtil.toJson(requestModel))
                        .syncRequest(false)
                        .onMainThread(true)
                        .timeOut(360000)
                        .execute(new SimpleCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean response) {
                                mMiniLoadingDialog.dismiss();
                                XToastUtils.success("提交成功", 3000);
//                                单工单提交后自动带出该产品的下一个工单号，不需返回第二个页面进行工单选择
//                                Intent intent = new Intent(FlexShelfOffOrderDetailActivity.this, FlexShelfOffOrderActivity.class);
//                                startActivity(intent);
                                setResult(RESULT_OK);
                                finish();
                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(FlexShelfOffOrderDetailLotNewActivity.this)
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(e.getMessage())
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });

            }
        });


        stvPKGNo.setOnKeyListener((view, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {

                if (StringUtils.equals("", stvPKGNo.getText().toString())) {
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.error("请先扫包号", 1500);
                    stvPKGNo.setText("");
                    stvPKGNo.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            stvPKGNo.requestFocus();
                        }
                    }, 200);
                    return false;
                }
                if (StringUtils.equals("", stvCarNo.getText().toString())) {
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.error("请先扫车号", 1500);
                    stvCarNo.requestFocus();
                    return false;
                }
                if (scanList.contains(stvPKGNo.getText().toString())) {
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.error("已扫描过该PKG/盘号", 1500);
                    stvPKGNo.setText("");
                    stvPKGNo.setText("");
                    stvPKGNo.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            stvPKGNo.requestFocus();
                        }
                    }, 200);
                    return false;
                }


                String str1 = stvOrderQty.getText().toString();
                int num1 = Integer.parseInt(str1);

                if (!StringUtils.isEmpty(stvFeedingQty.getText().toString())) {

                    int num2 = (int) Math.round(Double.parseDouble(stvFeedingQty.getText().toString()));

                    if (num1 <= num2) {
                        MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                        mp.start();
                        XToastUtils.error("已扫描数量不能大于计划数量", 1500);
                        stvPKGNo.setText("");
                        stvPKGNo.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stvPKGNo.requestFocus();
                            }
                        }, 200);
                        return false;
                    }
                }

                String Type = "";

                if (stvPKGNo.getText().toString().contains("PKG")) {
                    Type = "PKG";
                } else {
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.error("包属性是LOT，不允许扫PKG", 1500);
                    stvPKGNo.setText("");
                    stvPKGNo.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            stvPKGNo.requestFocus();
                        }
                    }, 200);
                    return false;
                }
                //检查数量格式
                String scanPlateQtyStr = ScanPlateQty.getText().toString();
                if (!scanPlateQtyStr.matches("^\\d+/\\d+$")) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.error("LOT下料数格式错误，应为数字/数字", 1500);
                    ScanPlateQty.setText("");
                    ScanPlateQty.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ScanPlateQty.requestFocus();
                        }
                    }, 200);
                    return false;
                }

                mMiniLoadingDialog.show();
                XHttp.get("api/WHSmartWhousePDA/GetPackageInfo")
                        .params("TaskNo", TaskNo)
                        .params("PackageNumber", stvPKGNo.getText().toString())
//                        .params("VehicleNumber", stvVehicleNo.getText().toString())
                        .params("CarNo", stvCarNo.getText().toString())
                        .params("Type", Type)
                        .syncRequest(false)
                        .onMainThread(true)
                        .timeOut(120000)
                        .execute(new SimpleCallBack<List<WHPKGLocData>>() {
                            @Override
                            public void onSuccess(List<WHPKGLocData> response) {
                                mMiniLoadingDialog.dismiss();
                                //判断涨缩值是否一致
                                if (!StringUtils.equals(ShrinkType, response.get(0).getShrinkType())) {
                                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                    mp.start();
                                    XToastUtils.error("涨缩值不一致，请检查", 1500);
                                    stvPKGNo.setText("");
                                    stvPKGNo.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            stvPKGNo.requestFocus();
                                        }
                                    }, 200);
                                    return;
                                }
                                BigDecimal scanQtyBigDecimal;
                                BigDecimal goodQtyBigDecimal;
                                if (StringUtils.isEmpty(ScanPlateQty.getText().toString())) {
                                    scanQtyBigDecimal = new BigDecimal(stvFeedingQty.getText().toString());
                                    goodQtyBigDecimal = new BigDecimal(response.get(0).getGoodQty());
                                    if(scanQtyBigDecimal.compareTo(new BigDecimal(response.get(0).getGoodQty())) > 0) {
                                        MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                        mp.start();
                                        XToastUtils.error("成品数量不能大于" + response.get(0).getGoodQty(), 1500);
                                        stvPKGNo.setText("");
                                        stvPKGNo.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                stvPKGNo.requestFocus();
                                            }
                                        }, 200);
                                        return;
                                    }
                                } else {
                                    String[] arrary =  ScanPlateQty.getText().toString().split("/");
                                    scanQtyBigDecimal = new BigDecimal(ScanPlateQty.getText().toString());
                                    goodQtyBigDecimal = new BigDecimal(arrary[0]);
                                    BigDecimal DefectQtyBigDecimal = new BigDecimal(arrary[1]);
                                    if(scanQtyBigDecimal.compareTo(new BigDecimal(response.get(0).getGoodQty())) > 0) {
                                        MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                        mp.start();
                                        XToastUtils.error("成品数量不能大于" + response.get(0).getGoodQty(), 1500);
                                        stvPKGNo.setText("");
                                        stvPKGNo.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                stvPKGNo.requestFocus();
                                            }
                                        }, 200);
                                        return;
                                    }
                                    if(DefectQtyBigDecimal.compareTo(new BigDecimal(response.get(0).getDefectQty())) < 0) {
                                        MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                        mp.start();
                                        XToastUtils.error("次品数量不能小于" + response.get(0).getDefectQty(), 1500);
                                        stvPKGNo.setText("");
                                        stvPKGNo.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                stvPKGNo.requestFocus();
                                            }
                                        }, 200);
                                        return;
                                    }
                                }

                                if (scanQtyBigDecimal.add(goodQtyBigDecimal).compareTo(new BigDecimal(10000)) > 0) {
                                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                    mp.start();
                                    XToastUtils.error("下工单需求数量不能大于10000", 1500);
                                    stvPKGNo.setText("");
                                    stvPKGNo.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            stvPKGNo.requestFocus();
                                        }
                                    }, 200);
                                    return;
                                }



                                boolean flag = false;
                                for (TaskPKGInfo taskPKGInfo : taskPKGInfoList) {
                                    if (StringUtils.equals(taskPKGInfo.getPKGNo(), response.get(0).getPackNO())) {
                                        taskPKGInfo.setChecked(true);
                                        flag = true;
                                        break;
                                    }
                                }
                                if (!flag) {
                                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                    mp.start();
                                    XToastUtils.error("该PKG:" + stvPKGNo.getText().toString() + "不属于该工单", 1500);
                                    stvPKGNo.setText("");
                                    stvPKGNo.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            stvPKGNo.requestFocus();
                                        }
                                    }, 200);
                                    return;
                                }

                                FlexShelfOffOrderDetailNewAdapter FlexShelfOffOrderDetailNewAdapter = new FlexShelfOffOrderDetailNewAdapter(FlexShelfOffOrderDetailLotNewActivity.this, taskPKGInfoList);
                                lvList.setAdapter(FlexShelfOffOrderDetailNewAdapter);

                                for(WHPKGLocData whpkgLocData : response) {
                                    whpkgLocData.setGoodQty(ScanPlateQty.getText().toString().split("/")[0]);
                                    whpkgLocData.setDefectQty(ScanPlateQty.getText().toString().split("/")[1]);
                                }
                                whpkgLocDataList.addAll(response);
                                stvFeedingQty.setText(scanQtyBigDecimal.add(goodQtyBigDecimal).toString());
                                scanList.add(stvPKGNo.getText().toString());
                                stvPKGNo.setText("");
                                stvPKGNo.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        stvPKGNo.requestFocus();
                                    }
                                }, 200);

                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                stvPKGNo.setText("");
                                stvPKGNo.requestFocus();
                                MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(view.getContext())
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(Objects.requireNonNull(e.getMessage()))
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });
            }
            return false;
        });
        ScanPlateQty.setOnKeyListener((view, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                //检查数量格式
                String scanPlateQtyStr = ScanPlateQty.getText().toString();
                if (!scanPlateQtyStr.matches("^\\d+/\\d+$")) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.error("LOT下料数格式错误，应为数字/数字", 1500);
                    ScanPlateQty.setText("");
                    ScanPlateQty.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ScanPlateQty.requestFocus();
                        }
                    }, 200);
                    return false;
                }
            }
            return false;
        });
        stvCarNo.setOnKeyListener((view, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                mMiniLoadingDialog.show();
                if (StringUtils.equals("", stvCarNo.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.error("请先扫车号", 1500);
                    stvCarNo.requestFocus();
                    return false;
                }
                XHttp.get("api/WHSmartWhousePDA/GetScanCarNumber")
                        .params("CarNumber", stvCarNo.getText().toString())
                        .syncRequest(false)
                        .onMainThread(true)
                        .timeOut(120000)
                        .execute(new SimpleCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean response) {
                                mMiniLoadingDialog.dismiss();
                                stvPKGNo.setText("");
                                stvPKGNo.requestFocus();
                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                stvCarNo.setText("");
                                stvCarNo.requestFocus();
                                MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailLotNewActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(view.getContext())
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(Objects.requireNonNull(e.getMessage()))
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });
            }
            return false;
        });


    }
}